package com.newland.mesdk.demo.activity;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.newland.mesdk.demo.main.R;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtype.module.common.pin.AccountInputType;
import com.newland.mtype.module.common.pin.K21PininutEvent;
import com.newland.mtype.module.common.pin.KeyManageType;
import com.newland.mtype.module.common.pin.PinConfirmType;
import com.newland.mtype.module.common.pin.PinInputEvent;
import com.newland.mtype.module.common.pin.WorkingKey;
import com.newland.mtype.util.ISOUtils;
import com.newland.mesdk.demo.interfaceimpl.K21PininputInterfaceImpl;
import com.newland.mesdk.demo.interfaceimpl.N900PinInputInterfaceImpl;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.main.MyApplication;
import com.newland.mesdk.demo.util.Const;

/**
 * Ｎ９００随机密码键盘页面
 */
public class N900KeyBoardNumberActivity extends Activity {
	private static final String TAG = "KeyBoardNumber";
	private K21PininputInterfaceImpl k21PininputInterfaceImpl;
	MainActivity mainActivity;
	/** 键盘按键 */
	private ImageView iv0;
	/** 键盘按键 */
	private ImageView iv1;
	/** 键盘按键 */
	private ImageView iv2;
	/** 键盘按键 */
	private ImageView iv3;
	/** 键盘按键 */
	private ImageView iv4;
	/** 键盘按键 */
	private ImageView iv5;
	/** 键盘按键 */
	private ImageView iv6;
	/** 键盘按键 */
	private ImageView iv7;
	/** 键盘按键 */
	private ImageView iv8;
	/** 键盘按键 */
	private ImageView iv9;

	/** 密码 */
	private TextView txtPassword;
	private StringBuffer buffer;
	private int inputLen = 0;

	/** 图片资源 */
	public final int[] resImages = { R.drawable.keyboard_0, R.drawable.keyboard_1, R.drawable.keyboard_2, R.drawable.keyboard_3,
			R.drawable.keyboard_4, R.drawable.keyboard_5, R.drawable.keyboard_6, R.drawable.keyboard_7, R.drawable.keyboard_8, R.drawable.keyboard_9 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.input_pin_fragment);
		k21PininputInterfaceImpl = new K21PininputInterfaceImpl();
		mainActivity=new MainActivity();
		Log.i(TAG, "Oncreate:");
		init();

	}

	private void init() {
		String accNo = getIntent().getStringExtra("accNo");
		txtPassword = (TextView) findViewById(R.id.txt_password);
		iv0 = (ImageView) findViewById(R.id.iv_0);
		iv1 = (ImageView) findViewById(R.id.iv_1);
		iv2 = (ImageView) findViewById(R.id.iv_2);
		iv3 = (ImageView) findViewById(R.id.iv_3);
		iv4 = (ImageView) findViewById(R.id.iv_4);
		iv5 = (ImageView) findViewById(R.id.iv_5);
		iv6 = (ImageView) findViewById(R.id.iv_6);
		iv7 = (ImageView) findViewById(R.id.iv_7);
		iv8 = (ImageView) findViewById(R.id.iv_8);
		iv9 = (ImageView) findViewById(R.id.iv_9);
		getRandomKeyBoardNumber();

		k21PininputInterfaceImpl.startK21StandPininput(null, new WorkingKey(Const.PinWKIndexConst.DEFAULT_PIN_WK_INDEX), KeyManageType.MKSK,
				AccountInputType.USE_ACCOUNT, accNo, 6, null, new byte[] { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F' },
				PinConfirmType.ENABLE_ENTER_COMMANG, 60, TimeUnit.SECONDS, null, null, pinInputListener);

	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2: // 键盘输入
				int len = (Integer) msg.obj;
				buffer = new StringBuffer();
				for (int i = 0; i < len; i++) {
					buffer.append(" * ");
				}
				txtPassword.setText(buffer.toString());
				break;

			default:
				break;
			}
		}
	};

	/**
	 * 获取随机键盘数字
	 * 
	 * @return
	 */
	private void getRandomKeyBoardNumber() {
		try {
			// 坐标基点
			int x0 = 0, x1 = 136, x2 = 270, x3 = 405, x4 = 535;
			int y0 = 494, y1 = 592, y2 = 689, y3 = 795, y4 = 887;
			int[] coordinateInt = new int[] { x0, y0, x1, y1, x1, y0, x2, y1, x2, y0, x3, y1, x3, y0, x4, y1, x0, y1, x1, y2, x1, y1, x2, y2, x2, y1,
					x3, y2, x3, y1, x4, y2, x0, y2, x1, y3, x1, y2, x2, y3, x2, y2, x3, y3, x0, y3, x1, y4, x1, y3, x2, y4, x2, y3, x3, y4, x3, y2,
					x4, y4, };
			// 初始坐标集合
			byte[] initCoordinate = new byte[coordinateInt.length * 2];
			for (int i = 0, j = 0; i < coordinateInt.length; i++, j++) {
				initCoordinate[j] = (byte) ((coordinateInt[i] >> 8) & 0xff);
				j++;
				initCoordinate[j] = (byte) (coordinateInt[i] & 0xff);
			}
			Log.i(TAG, "初始坐标:" + ISOUtils.hexString(initCoordinate));
			// 获取随机键盘键值
			byte[] randomCoordinate = N900PinInputInterfaceImpl.INSTANCE.loadRandomKeyboard(initCoordinate);
			StringBuilder sb = new StringBuilder();
			byte[] numserial = new byte[10];// 获取数字键
			int d = 0;
			for (int i = 0; i < randomCoordinate.length; i++) {
				if (i == 3 || i == 7 || i == 11 || i == 13 || i == 14) {
					continue;
				}
				numserial[d] = (byte) (randomCoordinate[i] & 0x0f);
				sb.append(numserial[d]);
				d++;
			}

			Log.i(TAG, "随机数字：" + sb.toString());
			// 处理图片
			ImageView[] buttons = new ImageView[] { iv1, iv2, iv3, iv4, iv5, iv6, iv7, iv8, iv9, iv0 };
			for (int i = 0; i < buttons.length; i++) {
				int number = Integer.valueOf(sb.charAt(i) + "");
				buttons[i].setImageResource(resImages[number]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private DeviceEventListener<K21PininutEvent> pinInputListener = new DeviceEventListener<K21PininutEvent>() {
		@Override
		public Handler getUIHandler() {
			return null;
		}

		@Override
		public void onEvent(K21PininutEvent event, Handler h) {
			if (event.isProcessing()) {// 正在输入
				Log.i(TAG, "is Processing");
				PinInputEvent.NotifyStep notifyStep = event.getNotifyStep();
				if (notifyStep == PinInputEvent.NotifyStep.ENTER) {
					inputLen = inputLen + 1;
					Log.i(TAG, "按了密码键:" + inputLen);
				} else if (notifyStep == PinInputEvent.NotifyStep.BACKSPACE) {
					inputLen = (inputLen <= 0 ? 0 : inputLen - 1);
					Log.i(TAG, "按了退格键:" + inputLen);
				}
				Message msg = mHandler.obtainMessage(2);
				msg.obj = inputLen;
				msg.sendToTarget();

			} else if (event.isUserCanceled()) {// 取消
				Log.i(TAG, "Is UserCanceled");
				finish();
			} else if (event.isSuccess()) {// 确定
				Log.i(TAG, "Is Success");
				if (event.getInputLen() == 0) {
					Log.i(TAG, "输入为空");
					finish();
				} else {
					// 输入成功
					byte[] pin = event.getEncrypPin();
					((MyApplication) N900KeyBoardNumberActivity.this.getApplication()).setPin(event.getEncrypPin());
					Log.i(TAG, "输入成功：" + ISOUtils.hexString(pin));
					Intent i = new Intent();
					i.putExtra("pin", pin);
					setResult(RESULT_OK, i);
					finish();
				}
			} else {
				Log.i(TAG, "密码输入异常", event.getException());
				finish();
			}
		}
	};
}
